package com.zhengtoudai.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;

import com.zhengtoudai.R;
import com.zhengtoudai.global.Config;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class StartPageActivity extends AppCompatActivity {
    private Subscription subscription;

    private final int REQUEST_CODE = 1;

    private List<String> hintPermissions; //拒绝并且不再询问后权限的提示文字集合

    private boolean isResume=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_page);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 设置状态栏透明
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        requestPermissions();
    }



    private void initView(final long time) {
         subscription=Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                try {
                    Thread.sleep(time);
                    subscriber.onNext(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .unsubscribeOn(Schedulers.io())
        .subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                startActivity(new Intent(StartPageActivity.this,MainActivity.class));
                finish();
            }
        });

        crateBaseFolder();
    }

    private void requestPermissions() {
        boolean writePermission= ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
        boolean readPhonePermission=ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_PHONE_STATE)
                ==PackageManager.PERMISSION_GRANTED;
        if (Build.VERSION.SDK_INT < 23||writePermission&&readPhonePermission){
            //授权成功
            initView(3000);
        }else{
            List<String> mList=new ArrayList();
            if (!writePermission){
                mList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (!readPhonePermission){
                mList.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (mList.size()>0){
                ActivityCompat.requestPermissions(this,mList.toArray(new String[]{}), REQUEST_CODE);
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == REQUEST_CODE) {
            List<String> deniedPermission=new ArrayList<>();
            for (int i=0;i<grantResults.length;i++){
                if(grantResults[i] == PackageManager.PERMISSION_GRANTED) {//授权成功
                    initView(2000);
                }else if (grantResults[i] == PackageManager.PERMISSION_DENIED){//点击拒绝授权

                    if (ActivityCompat.shouldShowRequestPermissionRationale(this
                            , permissions[i])) {//点击拒绝，再次弹出
                        deniedPermission.add(permissions[i]);
                        //ActivityCompat.requestPermissions(this, new String[]{permissions[i]}, REQUEST_CODE);
                    }else{ // 选择不再询问，并点击拒绝，弹出提示框
                        if (hintPermissions==null){
                            hintPermissions=new ArrayList<>();
                        }
                        if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                            hintPermissions.add("读写存储权限");
                        }else if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE)){
                            hintPermissions.add("读取手机状态权限");
                        }
                    }
                }
            }
            if (deniedPermission.size()>0){
                ActivityCompat.requestPermissions(this, deniedPermission.toArray(new String[]{}), REQUEST_CODE);
            }else if (hintPermissions!=null&&hintPermissions.size()>0){
                StringBuilder sb=new StringBuilder();
                for (int i=0;i<hintPermissions.size();i++){
                    sb.append(i<hintPermissions.size()-1?hintPermissions.get(i)+"、":hintPermissions.get(i));
                }
                showAlertDialog("为了您能正常使用"+getString(R.string.app_name)+",请开启"+sb.toString(), "取消", "手动授权", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri=Uri.parse("package:"+getPackageName());//包名，指定该应用"com.yingke.teyi"
                        Intent intent=new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
                        startActivity(intent);
                        isResume=true;
                        hintPermissions.clear();
                    }
                });
            }
            Log.e("grantResults","授权结果"+(grantResults[0] == PackageManager.PERMISSION_GRANTED));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isResume){
            requestPermissions();
            isResume=false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscription.isUnsubscribed()){
            subscription.unsubscribe();
        }
    }

    /**
     *
     * @param message  提示信息
     * @param btnNegative  取消按钮
     * @param btnPositive  确认按钮
     * @param positiveListener 确认按钮点击事件
     * @return
     */
    public AlertDialog.Builder showAlertDialog(String message, String btnNegative, String btnPositive, Dialog.OnClickListener positiveListener){
        final AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("温馨提示");
        builder.setMessage(message);
        builder.setNegativeButton(btnNegative, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setPositiveButton(btnPositive,positiveListener);
        builder.setCancelable(false);
        builder.show();
        return  builder;
    }

    /**
     * 创建基础文件夹
     */
    private void crateBaseFolder(){
        File file=new File(Environment.getExternalStorageDirectory(), Config.base_data_path);
        if (!file.exists()){
            file.mkdirs();
        }
    }
}
